package com.taijihuabao.modules.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.taijihuabao.common.commonutils.RandomValidateCodeUtil;
import com.taijihuabao.common.emailutils.EmailPojo;
import com.taijihuabao.common.exception.ServiceException;
import com.taijihuabao.common.jsonresult.ApplicationResponseCode;
import com.taijihuabao.common.rabbitmq.RabbitMqProducer;
import com.taijihuabao.modules.entity.ResendMessageEntity;
import com.taijihuabao.modules.mapper.ResendMessageMapper;
import com.taijihuabao.modules.model.resendmessage.dto.ResendMessageCrDTO;
import com.taijihuabao.modules.model.resendmessage.vo.ResendMessageListVO;
import com.taijihuabao.modules.service.ResendMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * 消息重发
 *
 * @author Tu
 * @date 2021/12/23 15:40
 */
@Service
public class ResendMessageServiceImpl implements ResendMessageService {

    private static final String RESEND_MESSAGE_PREFIX = "ResendMessage-";

    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Resource
    private ResendMessageMapper resendMessageMapper;
    @Resource
    private RabbitMqProducer rabbitMqProducer;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public List<ResendMessageListVO> selResendMessageList() {
        List<ResendMessageEntity> msgEntityList = resendMessageMapper.selResendMessageList();
        List<ResendMessageListVO> msgVoList = new ArrayList<>(msgEntityList.size());
        for (int i = 0; i < msgEntityList.size(); i++) {
            ResendMessageListVO msgVo = new ResendMessageListVO();
            msgVo.setId(msgEntityList.get(i).getId());
            msgVo.setMessageId(msgEntityList.get(i).getMessageId());
            try {
                msgVo.setSendMessage(objectMapper.readValue(msgEntityList.get(0).getMessageByteArray(), EmailPojo.class));
            } catch (IOException ioException) {
                throw new ServiceException(ApplicationResponseCode.INTER_ERROR);
            }
            msgVo.setMessageReason(msgEntityList.get(i).getMessageReason());
            msgVo.setDeadTime(msgEntityList.get(i).getDeadTime());
            msgVo.setDeadCount(msgEntityList.get(i).getDeadCount());
            msgVo.setFormerExchange(msgEntityList.get(i).getFormerExchange());
            msgVo.setFormerQueue(msgEntityList.get(i).getFormerQueue());
            msgVo.setFormerRoutingKey(msgEntityList.get(i).getFormerRoutingKey());
            msgVoList.add(msgVo);
        }
        return msgVoList;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void resendMessage(ResendMessageCrDTO resendMessageCrDTO) {
        ResendMessageEntity resendMessageEntity = resendMessageMapper.selResendMessageByMsgId(resendMessageCrDTO.getMessageId());
        if (StringUtils.isEmpty(resendMessageCrDTO.getMessageId()) || resendMessageEntity == null) {
            throw new ServiceException(ApplicationResponseCode.MESSAGE_NOT_EXIST);
        }
        try {
            EmailPojo emailPojo = objectMapper.readValue(resendMessageEntity.getMessageByteArray(), EmailPojo.class);
            int random = RandomValidateCodeUtil.sixMathValidateCode();
            String resendMassageContent = "消息重发，您的业务验证码为：" + random + "，" + RabbitMqProducer.OUT_TIME + "分钟内有效。切勿将验证码告知他人。";
            emailPojo.setContent(resendMassageContent);
            rabbitMqProducer.resendMessageCommon(resendMessageCrDTO.getMessageId(), emailPojo);
            redisTemplate.opsForValue().set(RESEND_MESSAGE_PREFIX + emailPojo.getReceiver().get(0), random, Duration.ofMinutes(RabbitMqProducer.OUT_TIME));
            resendMessageMapper.delete(resendMessageCrDTO.getMessageId());
        } catch (IOException ioException) {
            throw new ServiceException(ApplicationResponseCode.INTER_ERROR);
        }
    }

}
